package com.lagou.sqlsession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.util.GenericTokenParser;
import com.lagou.util.ParameterMapping;
import com.lagou.util.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    private final Configuration configuration;

    protected Transaction transaction;

    private Connection connection ;


    public SimpleExecutor(Configuration configuration) throws SQLException {
        this.configuration = configuration;
        //1、注册驱动，获取连接
        this.connection = configuration.getDataSource().getConnection();
        connection.setAutoCommit(false);
        //创建事务管理对象
        transaction=new JdbcTransaction(connection,configuration.getDataSource());
    }



    public <E> List<E> query( MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
        PreparedStatement preparedStatement=getPrepareStatement(mappedStatement,params);
//        List<?> objects=new ArrayList<?>();
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> classType = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<Object>();
        while (resultSet.next()){
            Object o = classType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <=metaData.getColumnCount() ; i++) {
                String name = metaData.getColumnName(i);
                Object object = resultSet.getObject(name);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, classType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,object);
            }
            objects.add(o);
        }


        //6、执行SQL

        //7、封装返回结果集


        return (List<E>) objects;
    }

    private PreparedStatement getPrepareStatement(MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        //2、获取SQL语句
        //3、转换SQL语句
        String sql=mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //4、获取预处理对象 prepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //5、设置参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> aClass=getClassType(paramterType);
        for (int i = 0; i < boundSql.getParameterMappings().size(); i++) {
            ParameterMapping parameterMapping = boundSql.getParameterMappings().get(i);

            Field declaredField = aClass.getDeclaredField(parameterMapping.getContent());
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }

        return preparedStatement;
    }

    @Override
    public int update(MappedStatement mappedStatement, Object... params) throws SQLException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
        return doUpdate(mappedStatement,params);
    }

    private  int doUpdate(MappedStatement ms,  Object... params) throws SQLException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
        PreparedStatement preparedStatement=getPrepareStatement(ms,params);
        int result = preparedStatement.executeUpdate();
//        preparedStatement
        return result;
    }


    @Override
    public void commit() throws SQLException {
        transaction.commit();
    }

    @Override
    public void rollback() throws SQLException {
        transaction.rollback();
    }

    private Class<?> getClassType( String paramterType ) throws ClassNotFoundException {
        Class<?> aClass=null;
        if (paramterType!=null)
            aClass=  Class.forName(paramterType);
        return aClass;
    }


    /**
     * 完成对#{}的解析工作 1、替换#{} 2、取出#{}里面的值并且进行存储
     * @param sql
     * @return
     */
    private  BoundSql getBoundSql(String sql){
        ParameterMappingTokenHandler tokenHandler=new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser=new GenericTokenParser("#{","}",tokenHandler);
        String sqlText=genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings=tokenHandler.getParameterMappings();
        BoundSql boundSql=new BoundSql(sqlText,parameterMappings);
        return  boundSql;
    }
}
